<?php
if (!defined('HAPPY')) exit("Access Denied");
/**************************
@Author  : sulwan
@Content : mysql操作链接类
**************************/
class Happy_Mysql {
	private $db_host; //数据库主机
	private $db_user; //数据库用户名
	private $db_pwd; //数据库用户名密码
	private $db_database; //数据库名
	private $mysql_link;//数据链接类型
	private $code;//编码
	private $sql;//要执行的语句
	private $result;//资源标识符
	private $insert_id;

	/*构造函数*/
	public function __construct($config) {
		$this->db_host = $config['host'];
		$this->db_user = $config['db_user'];
		$this->db_pwd = $config['password'];
		$this->db_database = $config['db_database'];
		$this->code = $config['code'];
        $this->tablepre = $config['tablepre'];
		$this->conn = '';
		$this->mysql_db_connect();
	}

	/*链接数据库*/
	public function mysql_db_connect() {
		switch($this->conn) {
		case 'pconnect':
			$this->mysql_link = mysql_pconnect ($this->db_host, $this->db_user, $this->db_pwd);
		default:
			$this->mysql_link = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
		}
		mysql_select_db($this->db_database,$this->mysql_link) or die ('Can\'t use '.$this->db_database.' : ' . mysql_error());
		mysql_query("SET NAMES $this->code");
	}

	/*执行语句*/
	public function mysql_db_query_sql($sql) {
		if(empty($sql)) {
			die('执行语句不能为空');
		}
        $sql = str_replace('#happy_', $this->tablepre, $sql);
		$this->sql = $sql;
		if($this->mysql_link){
			$this->mysql_db_connect();
		}
		$result = mysql_query($this->sql, $this->mysql_link) or die("Invalid query: " . mysql_error());
		$this->result = $result;
		$this->insert_id = mysql_insert_id($this->mysql_link);
		return $this->result;
	}

	/*取得数据结果集*/
	public function mysql_db_fetch_assoc() {
		return mysql_fetch_assoc($this->result);
	}
	/*返回一个单行结果集*/
	public function mysql_db_fetch_all() {
		while( $row = mysql_fetch_assoc($this->result)){
				$result[]=$row;
		}
		return $result;
	}


	/*返回一个数字结果集*/
	public function mysql_db_fetch_all_num() {
		while( $row = mysql_fetch_row($this->result)){
				$result[]=$row;
		}
		return $result;
	}


	/*返回本次执行ID*/
	public function mysql_db_insert_id() {
		return $this->insert_id;
	}

	/*释放资源*/
	public function mysql_db_free() {
		@mysql_free_result($this->result);
	}

    /*获取数据库版本*/
    public function version() {
		return mysql_get_server_info($this->mysql_link);
	}


    /*资源*/
    public function mysql_db_fetch_row() {
		return mysql_fetch_row($this->result);
	}


	function num_rows() {
		return mysql_num_rows($this->result);
	}

	function num_fields() {
		return mysql_num_fields($this->result);
	}
	/*析构函数*/
	public function __destruct() {
		if($this->result) {
			$this->mysql_db_free();
		}
		@mysql_close($this->mysql_link);
	}
}
?>